Views in Django

Manish Patel

Aug 25, 2023

Views in Django

  • In Django, views are responsible for processing HTTP requests and returning appropriate HTTP responses.
  • Django offers different types of views to handle various use cases:
  1. Function-based views,
  2. Class-based views, and
  3. Generic class-based views.

Each type of view has its own benefits and use cases.

1. Function-Based Views (FBVs):

  • Function-based views are the simplest form of views in Django.
  • They are defined as regular Python functions that take an HTTP request as input and return an HTTP response.
  • FBVs are straightforward and work well for handling basic use cases.
from django.shortcuts import render

def my_view(request):
   # Process the request
   return render(request, 'template.html', context)
  • Use FBVs when you have simple view logic and don’t need the additional features provided by class-based views.

2. Class-Based Views (CBVs):

  • Class-based views provide a more organized way to handle view logic by using class inheritance.

  • CBVs allow you to reuse common behavior using class inheritance, making it easier to manage and extend views with mixins and overrides.

    from django.views import View
    from django.shortcuts import render
    
    class MyView(View):
        def get(self, request):
            # Process the GET request
            return render(request, 'template.html', context)
  • CBVs are suitable when you want to structure your views using class inheritance and take advantage of built-in methods for different HTTP methods (e.g., get, post, etc.).

3. Generic Class-Based Views (GCBVs):

  • Generic class-based views are pre-built views provided by Django to handle common patterns, like displaying lists, details, creating, updating, and deleting objects.

  • They encapsulate common view logic and reduce code repetition.

    from django.views.generic import ListView, DetailView
    
    class BookListView(ListView):
        model = Book
        template_name = 'book_list.html'
        context_object_name = 'books'
  • GCBVs are particularly useful for standard operations like listing objects, displaying details, and performing CRUD operations. They reduce the need to write repetitive code.

Summary

  • Function-Based Views (FBVs) are simple functions that handle view logic and return responses.
  • Class-Based Views (CBVs) are organized using classes and offer flexibility for inheritance and customization.
  • Generic Class-Based Views (GCBVs) are pre-built views for common patterns, reducing code duplication and promoting best practices.

The choice between these types of views depends on - the complexity of your view logic, - the need for code organization and reuse, and - the availability of built-in functionality for your specific use case.

DJANGO PROJECT TO DEMONSTRATE VIEWS

  • A comprehensive example of function-based views, class-based views, and generic views.

  • We’ll create a simple blog post listing using class based, function based and generic views.

  • Follow these steps:

1. Create a New Django Project:

django-admin startproject ViewsDemoProjectCBV
cd ViewsDemoProjectCBV

2. Create a New App:

python manage.py startapp viewsdemocbv

3. Define Views:

  • In viewsdemocbv/views.py, define function-based and class-based views:
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django.views.generic import ListView
from .models import BlogPost

def fbv_greet(request):
   return HttpResponse("Hello from Function-Based View!")

class CBVGreetView(View):
   def get(self, request):
       return HttpResponse("Hello from Class-Based View!")

class BlogPostListView(ListView):
   model = BlogPost
   template_name = 'viewsdemocbv/blogpost_list.html'
   context_object_name = 'blogposts'

4. Configure URLs:

  • In viewsdemocbv/urls.py, set up URL patterns for FBV, CBV, and the generic view:
from django.urls import path
from . import views

urlpatterns = [
   path('fbv-greet/', views.fbv_greet, name='fbv_greet'),
   path('cbv-greet/', views.CBVGreetView.as_view(), name='cbv_greet'),
   path('blogposts/', views.BlogPostListView.as_view(), name='blogpost_list'),
]

5. Create Templates Directory:

  • Inside the viewsdemocbv app directory, create a templates directory. Inside the templates directory, create a viewsdemocbv subdirectory and add a file named blogpost_list.html:
ViewsDemoProjectCBV/
├── ViewsDemoProjectCBV/
│   ├── ...

├── viewsdemocbv/
│   ├── ...
│   └── templates/
│       └── viewsdemocbv/
│           └── blogpost_list.html, base.html,cbv_greet.html

├── manage.py
└── ...

6. Create Templates:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}ViewsDemo{% endblock %}</title>
</head>
<body>
    <header>
        <h1><a href="{% url 'fbv_greet' %}">ViewsDemo</a></h1>
        <nav>
            <ul>
                <li><a href="{% url 'fbv_greet' %}">FBV Greet</a></li>
                <li><a href="{% url 'cbv_greet' %}">CBV Greet</a></li>
                <li><a href="{% url 'blogpost_list' %}">Blog Posts</a></li>
            </ul>
        </nav>
    </header>
    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

7. cbv_greet.html

In cbv_greet.html, use Django template language to display a greeting for the CBV: In blogpost_list.html, use Django template language to display a list of blog posts:

{% extends 'base.html' %}

{% block content %}
<h1>Class-Based View Greeting</h1>
<p>{{ greeting }}</p>
{% endblock %}

<h1>Blog Posts</h1>
<ul>
    {% for blogpost in blogposts %}
        <li>{{ blogpost.title }} - {{ blogpost.author }} - {{ blogpost.date }}</li>
    {% endfor %}
</ul>

8. Create Models:

  • In viewsdemocbv/models.py, define a simple BlogPost model:
from django.db import models

class BlogPost(models.Model):
   title = models.CharField(max_length=200)
   author = models.CharField(max_length=100)
   date = models.DateField()

   def __str__(self):
       return self.title

9. Register model in admin.py

from django.contrib import admin
from . models import BlogPost
# Register your models here.
admin.site.register(BlogPost)

10. Migrate Database:

  • Run the migrations to create the database tables:
python manage.py makemigrations
python manage.py migrate

11. Configure URLs:

  • In ViewsDemoProjectCBV/urls.py, include the URLs from the viewsdemocbv app:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('viewsdemocbv/', include('viewsdemocbv.urls')),
]

12. URL PATTERNS

  • In viewsdemocbv/urls.py, set up URL patterns for FBV, CBV, and the generic view:

from django.urls import path
from . import views

urlpatterns = [
    path('fbv-greet/', views.fbv_greet, name='fbv_greet'),
    path('cbv-greet/', views.CBVGreetView.as_view(), name='cbv_greet'),
    path('blogposts/', views.BlogPostListView.as_view(), name='blogpost_list'),
]

13. Run the Development Server:

  • Start the development server:
python manage.py runserver

14. Access the Project:

Open your browser and visit -
- http://127.0.0.1:8000/viewsdemocbv/fbv-greet/
- http://127.0.0.1:8000/viewsdemocbv/cbv-greet/
- http://127.0.0.1:8000/viewsdemocbv/blogposts/